﻿Imports Heren.Common.Forms.Editor
Imports Heren.Common.Forms
Imports Heren.Common.ScriptEngine.Script
Imports Microsoft.VisualBasic
Imports System.Windows.Forms
Imports Heren.Common.Forms.Runtime
Imports System.Text
Imports Heren.Common.Libraries

Public Class 压疮发生率 : Inherits AbstractRuntimeHandler
    ''****************************************************************
    '' 这是护理电子病历表单后台运行支持脚本
    '' 注意：这是Visual Basic脚本，您可以不区分大小写 
    '' 请不要修改系统提供的方法名，以及方法名前面的Overrides关键字
    '' Script Language : Visual Basic
    '' Author : YangMingkun, Date : 2012-3-18
    '' Copyright (C) Heren Health Services (SUPCON) Co.,Ltd.
    ''****************************************************************


    '表单脚本初始化
    Public Overrides Sub Initialize()
        'Me.ShowMessage("表单已完成加载!")
        '在此函数中来查询和设置表单中的相关数据
        '可以调用GetSystemContext函数获取系统中已有数据，也可以从数据库中读取其他任意数据
        '    Me.Refresh(Nothing)
        Dim parent As Control = Me.FindControl("RootControl1")
        If (parent IsNot Nothing) Then
            parent.Dock = DockStyle.Fill
        End If

    End Sub

    Dim dtPatInfos As DataTable = Nothing
    Dim dtDeptInfos As DataTable = Nothing
    Dim dtSpePatientInfos As DataTable = Nothing

    '获取关键数据列表
    Public Overrides Function GetKeyDataList() As List(Of KeyData)
        Dim keyDataList As New List(Of KeyData)
        Return keyDataList
    End Function


    '更新表单中指定的数据
    Public Overrides Function UpdateFormData(ByVal param As String, ByVal data As Object) As Boolean
        '	Me.StartThread("查询数据")

        Dim datatable As DataTable = Nothing
        '获取病人数据
        datatable = GetPatientInfos()
        '获取科室数据（病区-科室）
        获取科室数据()
        获取压疮申请数据()
        '		showmessage(dtPatInfos.rows.count)
        '		showmessage(dtDeptInfos.rows.count)
        '		showmessage(dtSpePatientInfos.rows.count)
        '数据统计显示
        RefreshPatCount(datatable)

        Return True
    End Function


    '获取表单中指定的数据
    Public Overrides Function GetFormData(ByVal param As Object) As Object
        If param = "表单摘要" Then
            Return Me.GetFormSummary()
        End If
        Return Nothing
    End Function


    '获取表单摘要数据
    Public Function GetFormSummary() As String
        Dim control As Control = Me.FindControl("XTextBox1")
        If control IsNot Nothing Then
            Return control.Text
        End If
        Return String.Empty
    End Function


    '病区选择时刷新列表和统计信息
    Private Sub Refresh(ByVal dtWardInfos As DataTable)
        '1.根据病区读取病人数据
        Dim dtPatientInfos As DataTable = Nothing
        '    dtPatientInfos=Me.GetPatientInfos(dtWardInfos)
        If dtPatientInfos Is Nothing Then
            Return
        End If
        '2.刷新病人列表
        Me.RefreshDataGrid(dtPatientInfos)
        '3.刷新统计信息
        Me.RefreshStatistics(dtPatientInfos)
    End Sub

    '刷新病人列表
    Private Sub RefreshDataGrid(ByVal dtPatientInfos As DataTable)
        If dtPatientInfos Is Nothing Then
            Return
        End If
        Dim grid As XDataGrid = Me.FindControl("XDataGrid1")
        If grid Is Nothing OrElse grid.Columns.Count <= 0 Then
            Return
        End If
        grid.Rows.Clear()

        For Each row As DataRow In dtPatientInfos.Rows
            Dim rowIndex As Integer = grid.Rows.Add()
            SetCellValue(grid, rowIndex, 0, (rowIndex + 1).ToString())
            For i As Integer = 1 To dtPatientInfos.Columns.Count - 2
                If i = 5 Then
                    Me.SetCellValue(grid, rowIndex, i, Me.GetAgeText(row(i), DateTime.Now))
                Else
                    Me.SetCellValue(grid, rowIndex, i, row(i))
                End If
            Next
            grid.SetRowState(rowIndex, 0)
            grid.Rows(rowIndex).Tag = row
        Next
    End Sub
    '根据不同申报类型统计的病人列表
    Dim ReportTypePatient As New Dictionary(Of String, DataTable)
    '刷新统计信息
    Private Sub RefreshStatistics(ByVal dtPatientInfos As DataTable)
        If dtPatientInfos Is Nothing Then
            Return
        End If
        '带入压疮
        Dim OutPatientInfos As DataTable = dtPatientInfos.Copy()
        OutPatientInfos.Rows.Clear()
        '高危压疮
        Dim RiskPatientInfos As DataTable = dtPatientInfos.Copy()
        RiskPatientInfos.Rows.Clear()
        '不可避免压疮
        Dim UnavoidPatientInfos As DataTable = dtPatientInfos.Copy()
        UnavoidPatientInfos.Rows.Clear()
        '待审核
        Dim WaitPatientInfos As DataTable = dtPatientInfos.Copy()
        WaitPatientInfos.Rows.Clear()

        For Each dr As DataRow In dtPatientInfos.Rows
            Select Case Me.GetFieldValue(dr, "ReportType").ToString()
                Case "院外带入压疮"
                    OutPatientInfos.Rows.Add(dr.ItemArray)
                Case "高危备案"
                    RiskPatientInfos.Rows.Add(dr.ItemArray)
                Case "申报不可避免压疮"
                    UnavoidPatientInfos.Rows.Add(dr.ItemArray)
            End Select

            If Me.GetFieldValue(dr, "status_desc").ToString().Contains("审核中") Then
                WaitPatientInfos.Rows.Add(dr.ItemArray)
            End If
        Next
        ReportTypePatient.Clear()
        ReportTypePatient.Add("OutPatientInfos", OutPatientInfos)
        ReportTypePatient.Add("RiskPatientInfos", RiskPatientInfos)
        ReportTypePatient.Add("UnavoidPatientInfos", UnavoidPatientInfos)
        ReportTypePatient.Add("WaitPatientInfos", WaitPatientInfos)
        If OutPatientInfos IsNot Nothing Then
            Me.SetControlText("fbOut", "带入压疮：" + OutPatientInfos.Rows.Count.ToString())
        Else
            Me.SetControlText("fbOut", "带入压疮：0")
        End If

        If RiskPatientInfos IsNot Nothing Then
            Me.SetControlText("fbRisk", "高危压疮：" + RiskPatientInfos.Rows.Count.ToString())
        Else
            Me.SetControlText("fbRisk", "高危压疮：0")
        End If

        If UnavoidPatientInfos IsNot Nothing Then
            Me.SetControlText("fbUnavoid", "不可避免压疮：" + UnavoidPatientInfos.Rows.Count.ToString())
        Else
            Me.SetControlText("fbUnavoid", "不可避免压疮：0")
        End If

        If WaitPatientInfos IsNot Nothing Then
            Me.SetControlText("XFlatButton1", "待审核：" + WaitPatientInfos.Rows.Count.ToString())
        Else
            Me.SetControlText("XFlatButton1", "待审核：0")
        End If
    End Sub

    '根据时间区间读取病人数据
    Private Function GetPatientInfos() As DataTable
        Dim strWardCode As String = ""
        If dtDepts IsNot Nothing Then
            For Each dr As DataRow In dtDepts.Rows
                If strWardCode = "" Then
                    strWardCode = "and (t.WARD_CODE='" + Me.GetFieldValue(dr, 0).ToString() + "'"
                Else
                    strWardCode += "or t.WARD_CODE='" + Me.GetFieldValue(dr, 0).ToString() + "'"
                End If
            Next
        End If
        If strWardCode <> "" Then
            strWardCode = strWardCode + ")"
        End If
        '    showmessage(strWardCode.tostring())
        '    Dim strSql As New StringBuilder
        '    strSql.Append("select t.patient_id, t.visit_id, t.ward_code, p.apply_type,t.DISCHARGE_TIME ")
        '    strSql.Append(" from pat_visit_v t left join nur_apply_index p on t.PATIENT_ID = p.patient_Id and t.VISIT_ID = p.visit_id")
        '    
        Dim dtVisitStartTime As XDateTime = Me.FindControl("dtVisitStartTime")
        Dim dtVisitEndTime As XDateTime = Me.FindControl("dtVisitEndTime")

        Dim strSql As New StringBuilder
        strSql.Append("select A.patient_id, A.Visit_id, B.dept_stayed from PAT_VISIT@LINK_EMR A, transfer@link_emr B ")
        Dim Condition As String = ""
        Condition = Condition + " where A.ADMISSION_DATE_TIME >= to_date('" + dtVisitStartTime.Value.ToString() + "', 'yyyy/mm/dd hh24:mi:ss') and A.ADMISSION_DATE_TIME < to_date('"
        Condition = Condition + dtVisitEndTime.Value.ToString() + "', 'yyyy/mm/dd hh24:mi:ss') and  A.DISCHARGE_DATE_TIME is not null "
        Condition = Condition + "and A.patient_id = B.patient_id and A.Visit_id = B.Visit_id" + strWardCode + " order by B.dept_stayed "
        strSql.Append(Condition)
        'showmessage(strSql.tostring())
        Dim dtPatientInfos As DataSet = Nothing
        Me.ExecuteQuery(strSql.ToString(), dtPatientInfos)
        If dtPatientInfos Is Nothing OrElse dtPatientInfos.Tables.Count <= 0 Then
            Return Nothing
        End If
        dtPatInfos = dtPatientInfos.Tables(0)
        Return dtPatientInfos.Tables(0)
    End Function

    Private Sub 获取科室数据()
        Dim strSql As New StringBuilder
        strSql.Append("select t.ward_code,(select a.dept_name from DEPT_V a where t.ward_code=a.dept_code) as ward_name,t.dept_code, t.dept_name from DEPT_V t ")
        strSql.Append("where t.ward_code is not null order by t.ward_code ")
        Dim DeptInfos As DataSet = Nothing
        Me.ExecuteQuery(strSql.ToString(), DeptInfos)
        If DeptInfos Is Nothing OrElse DeptInfos.Tables.Count <= 0 Then
            Return
        End If
        dtDeptInfos = DeptInfos.Tables(0)
    End Sub

    Private Sub 获取压疮申请数据()
        Dim strSql As New StringBuilder
        strSql.Append("select distinct t.patient_id, t.visit_id from DOC_SUMMARY_DATA t ")
        strSql.Append("where t.data_name = 'ReportType' and t.data_value is not null")
        Dim SpePatientInfos As DataSet = Nothing
        Me.ExecuteQuery(strSql.ToString(), SpePatientInfos)
        If SpePatientInfos Is Nothing OrElse SpePatientInfos.Tables.Count <= 0 Then
            Return
        End If
        dtSpePatientInfos = SpePatientInfos.Tables(0)
    End Sub

    Private Sub RefreshPatCount(ByVal dtPatientInfos As DataTable)
        '	'清空数据
        Dim grid As XDataGrid = Me.FindControl("XDataGrid1")
        grid.Rows.Clear()

        If dtPatInfos.Rows.Count = 0 Or dtDeptInfos.Rows.Count = 0 Or dtSpePatientInfos.Rows.Count = 0 Then
            Return
        End If
        '新建数据缓存
        Dim list As New List(Of DeptInfo)
        '加载病区列表
        For Each Row As DataRow In dtDeptInfos.Rows
            DeptToFind = Row(0).ToString()
            Dim DeptNo As New DeptInfo
            DeptNo = list.Find(AddressOf FindDept)
            If DeptNo Is Nothing Then
                DeptNo = New DeptInfo
                DeptNo.DeptNo = Row(0).ToString()
                DeptNo.DeptName = Row(1).ToString()
                list.Add(DeptNo)
            End If
        Next

        For i As Integer = 0 To list.Count - 1
            For Each PatRow As DataRow In dtPatInfos.Rows
                If IsInWard(PatRow(2).ToString(), list(i).DeptNo.ToString()) Then

                    list(i).DischargeNo += 1
                    For Each SpePatRow As DataRow In dtSpePatientInfos.Rows
                        If SpePatRow(0).ToString() = PatRow(0).ToString() And SpePatRow(1).ToString() = PatRow(1).ToString() Then
                            list(i).DischatgePsNo += 1
                        End If
                    Next
                End If
            Next
        Next

        Dim j As Integer = 0
        For i As Integer = 0 To list.Count - 1
            If list(i).DischargeNo > 0 Then
                list(i).PsIncidence = (list(i).DischatgePsNo / list(i).DischargeNo) * 100
            Else : list(i).PsIncidence = 0
            End If
            If dtDepts IsNot Nothing Then
                For Each Row As DataRow In dtDepts.Rows
                    If Row(0) = list(i).DeptNo Then
                        grid.Rows.Add()
                        Me.SetCellValue(grid, j, 0, list(i).DeptName)
                        Me.SetCellValue(grid, j, 1, list(i).DischatgePsNo)
                        Me.SetCellValue(grid, j, 2, list(i).DischargeNo)
                        Me.SetCellValue(grid, j, 3, Math.Round(list(i).PsIncidence, 2).ToString() + "%")
                        j += 1
                    End If
                Next
            Else
                grid.Rows.Add()
                Me.SetCellValue(grid, i, 0, list(i).DeptName)
                Me.SetCellValue(grid, i, 1, list(i).DischatgePsNo)
                Me.SetCellValue(grid, i, 2, list(i).DischargeNo)
                Me.SetCellValue(grid, i, 3, Math.Round(list(i).PsIncidence, 2).ToString() + "%")
            End If
        Next i
    End Sub

    Private Function IsInWard(ByRef DeptCode As String, ByRef WardCode As String)
        For Each Row As DataRow In dtDeptInfos.Rows
            If Row(0).ToString() = WardCode And Row(2).ToString() = DeptCode Then
                Return True
            End If
        Next
        Return False
    End Function

    Private DeptToFind As String = ""
    Private Function FindDept(ByVal DeptNo As DeptInfo) As Boolean
        If DeptNo.DeptNo = DeptToFind Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Class DeptInfo
        Public DeptNo As String
        Public DeptName As String
        Public DischatgePsNo As Integer
        Public DischargeNo As Integer
        Public PsIncidence As Double
    End Class

    '带入压疮 统计数单击时发生。
    Private Sub fbOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        '带入压疮
        Dim OutPatientInfos As DataTable = Nothing
        If ReportTypePatient.ContainsKey("OutPatientInfos") Then
            OutPatientInfos = ReportTypePatient("OutPatientInfos")
        End If
        Me.RefreshDataGrid(OutPatientInfos)
    End Sub

    Private Sub fbRisk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        '高危压疮
        Dim RiskPatientInfos As DataTable = Nothing
        If ReportTypePatient.ContainsKey("RiskPatientInfos") Then
            RiskPatientInfos = ReportTypePatient("RiskPatientInfos")
        End If
        Me.RefreshDataGrid(RiskPatientInfos)
    End Sub

    '不可避免压疮 统计数单击时发生。
    Private Sub fbUnavoid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        '不可避免压疮
        Dim UnavoidPatientInfos As DataTable = Nothing
        If ReportTypePatient.ContainsKey("UnavoidPatientInfos") Then
            UnavoidPatientInfos = ReportTypePatient("UnavoidPatientInfos")
        End If
        Me.RefreshDataGrid(UnavoidPatientInfos)
    End Sub

    '单击组件时发生。
    Private Sub XFlatButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim WaitPatientInfos As DataTable = Nothing
        If ReportTypePatient.ContainsKey("WaitPatientInfos") Then
            WaitPatientInfos = ReportTypePatient("WaitPatientInfos")
        End If
        Me.RefreshDataGrid(WaitPatientInfos)
    End Sub

    '用户双击单元格中的任意位置时发生，打开相应的病人窗口
    Private Sub XDataGrid1_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)

    End Sub


    Dim dtDepts As DataTable = Nothing
    '双击组件时发生。
    Private Sub XTextBox1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        '调用科室选择窗口
        Dim control As Control = Me.FindControl("XTextBox1")
        '当前选中的护理单元
        Dim dtCurrentWardInfos As DataTable = Nothing
        If control IsNot Nothing Then
            dtCurrentWardInfos = control.Tag
        End If
        '传出选择的护理单元
        Dim strDeptNames As String = ""
        Me.RaiseCustomEvent(sender, "病区选择对话框", "true", dtCurrentWardInfos, dtCurrentWardInfos)
        If dtCurrentWardInfos IsNot Nothing Then
            For Each dr As DataRow In dtCurrentWardInfos.Rows
                If strDeptNames = "" Then
                    strDeptNames = Me.GetFieldValue(dr, 1)
                Else
                    strDeptNames += ";" + Me.GetFieldValue(dr, 1)
                End If
            Next
        End If
        If strDeptNames <> "" Then
            Me.SetControlText("XTextBox1", strDeptNames)
        Else
            Me.SetControlText("XTextBox1", "全院<可双击修改>")
        End If
        If control IsNot Nothing Then
            control.Tag = dtCurrentWardInfos
        End If
        dtDepts = dtCurrentWardInfos
        '   Me.Refresh(dtCurrentWardInfos)
    End Sub


    '单击组件时发生。
    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        '	If Me.isthreadrunning("查询数据") Then
        '        Me.showmessage("系统正在统计压疮发生率,请稍后...")
        '        Exit Sub
        '    End If
        '	Me.StartThread("查询数据")

        Dim datatable As DataTable = Nothing
        '获取病人数据
        datatable = GetPatientInfos()
        '获取科室数据（病区-科室）
        获取科室数据()
        获取压疮申请数据()
        '		showmessage(dtPatInfos.rows.count)
        '		showmessage(dtDeptInfos.rows.count)
        '		showmessage(dtSpePatientInfos.rows.count)
        '数据统计显示
        RefreshPatCount(datatable)
    End Sub


    '单击组件时发生。
    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim grid As XDataGrid = Me.FindControl("XDataGrid1")
        grid.Rows.Clear()
    End Sub


    '单击组件时发生。
    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim grid As XDataGrid = CType(Me.FindControl("XDataGrid1"), XDataGrid)

        '    Dim dataset As New XDataGrid 
        Dim dt As DataTable = Nothing
        dt = Me.GetDataTable(grid, 0, 0)
        If Me.ExportCsvFile(dt) = True Then
            ShowMessage("数据导出成功!")
        End If
    End Sub

    Protected Overrides Sub ThreadCallback(ByVal param As Object)
        If param = "查询数据" Then
            Dim datatable As DataTable = Nothing
            '获取病人数据
            datatable = GetPatientInfos()
            '获取科室数据（病区-科室）
            获取科室数据()
            获取压疮申请数据()
            '		showmessage(dtPatInfos.rows.count)
            '		showmessage(dtDeptInfos.rows.count)
            '		showmessage(dtSpePatientInfos.rows.count)
            '数据统计显示
            RefreshPatCount(datatable)
        End If
    End Sub


End Class
